package com.kx.yooli.kx.wechat.config.wx;
import com.google.gson.JsonObject;
import com.kx.yooli.kx.wechat.config.propertiesconf.CustomizedPropertyConfigurer;
import com.kx.yooli.kx.wechat.utils.comm.GsonUtils;
import com.kx.yooli.kx.wechat.utils.http.HttpUtils;
import com.kx.yooli.kx.wechat.utils.redis.RedisUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author john_sqwen-childe.wen
 * date 2024/5/30
 * PROJECT_NAME wechat
 * description create WechatInit by john_sqwen
 * and  value is
 */
@Component
public class WechatInit
{
    private final Logger log = LoggerFactory.getLogger(WechatInit.class);
    @Resource
    RedisUtil redisUtil;
    private String accessToken= "";
    /**
     * @author john_sqwen
     * @description 此方法是获取微信公众号的token
     * @param url appid,grant_type,secret 此三个参数 是必须要带入的，不然会返回错误的json 信息
     * @return jason
     *
     */
    public void obtainWechatToken(){
        String url = CustomizedPropertyConfigurer.getContextProperty("access.token.url");
        String appid =CustomizedPropertyConfigurer.getContextProperty("app.id");
        String secret = CustomizedPropertyConfigurer.getContextProperty("app.secret");
        log.info("appid {},secret{}",appid,secret);
        String lastUrl = url.replace("APPID", appid).replace("APPSECRET", secret);
        log.info("last url value is  {}",lastUrl);
        String s = HttpUtils.sendSsLPost(lastUrl);
        //将请求数据转成json
        var jsonObject = GsonUtils.strJsonObject(s);
        if(null == jsonObject.get("errcode") && jsonObject.isJsonObject()){
            if(!s.isBlank() && !s.isEmpty()){
                redisUtil.set("token",s);
                accessToken = s;
            }
            obtainGetMenus();
        }

    }
    /**
     * get  jsapi_ticket
     *
     */
    public void obtainJsApiTicket(){
        var url = CustomizedPropertyConfigurer.getContextProperty("jsapi.ticket.url");
        //判断 如果 当前 的accessToken 为空，则说明没有调用获取 accessToken方法
        if(accessToken.isEmpty() && accessToken.isBlank()){
            obtainWechatToken();
        }
        var jsonObject = GsonUtils.strJsonObject(accessToken);
        log.info("Gson jsonObject value is {},is jsonObject ?{}",jsonObject,jsonObject.isJsonObject());
        if(null == jsonObject.get("errcode") && jsonObject.isJsonObject()){
            var lastUrl =  url.replace("ACCESS_TOKE", accessToken);
            var result = HttpUtils.sendGet(lastUrl);
            if(!result.isBlank() && !result.isEmpty()){
                redisUtil.set("jsApi",result);
            }
        }
        log.info("公众号官方的返回是，请查看相关日志,{}",jsonObject);
    }

    /**
     * 获取 openId
     *
     */
    public void obtainOpenId(){
        var url = CustomizedPropertyConfigurer.getContextProperty("getOpenIdUrl");
        var appid = CustomizedPropertyConfigurer.getContextProperty("app.id");
        var secret = CustomizedPropertyConfigurer.getContextProperty("app.secret");
        var param = appid+"&secret="+secret+"&grant_type=authorization_code"+"code=code";
        var redisToken = GsonUtils.strJsonObject(redisUtil.get("token").toString());
        var redisBadToken = GsonUtils.strJsonObject(redisUtil.get("badToken").toString());
        var jsonToken =GsonUtils.strJsonObject(redisToken.toString()).get("access_token");
        var s = HttpUtils.sendGet(url, param);
       /* if(null == redisBadToken.get("errcode") && redisBadToken.isJsonObject() && null == jsonToken.get("errcode") && jsonToken.isJsonObject()) {
            var s = HttpUtils.sendGet(url, param);
            var jsonObject = GsonUtils.strJsonObject(s);
            if (null == jsonObject.get("errcode") && jsonObject.isJsonObject()) {
                redisUtil.set("openId", s);
            }
            log.info("公众号官方的返回是，请查看相关日志,{}", jsonObject);
        }*/
    }

    /**
     * 获取 自定义menu 并存入到 redis 中
     * @param accessToken
     * @return json
     */
    public void obtainGetMenus(){
        var url = CustomizedPropertyConfigurer.getContextProperty("menu.query.url");
        if(accessToken.isEmpty() && accessToken.isBlank()){
            obtainWechatToken();
        }
        var jsonToken = GsonUtils.strJsonObject(accessToken);
        if(null !=jsonToken && jsonToken.isJsonObject() && null == jsonToken.get("errcode")) {
            var lastUrl = url.replace("ACCESS_TOKEN",jsonToken.get("access_token").toString()).replaceAll("\"","");
            var s = HttpUtils.sendGet(lastUrl);
            var jsonObject = GsonUtils.strJsonObject(s);
            log.info("jsonObject value is {},s value is {}",jsonObject,s);
                boolean menusQuery = redisUtil.set("menus_query", s);
                if(menusQuery) {
                    //obtainDeleteMenus();
                }
            Object menusQuery1 = redisUtil.get("menus_query");
            JsonObject jsonObject1 = GsonUtils.strJsonObject(String.valueOf(menusQuery1));
            log.info("select  server return value is  {}",jsonObject1);
            log.info("公众号返回的数据为:{}",s);
        }
    }

    /**
     * 删除菜单
     * @param  accessToken
     * @return  json
     */
    public void obtainDeleteMenus(){
        var url = CustomizedPropertyConfigurer.getContextProperty("menu.delete.url");
        if(accessToken.isEmpty() && accessToken.isBlank()){
            obtainWechatToken();
        }
        //var redisToken = GsonUtils.strJsonObject(redisUtil.get("token").toString());
        var jsonToken = GsonUtils.strJsonObject(accessToken);
        if(null!=jsonToken && jsonToken.isJsonObject() && null == jsonToken.get("errcode")) {
            var lastUrl = url.replace("ACCESS_TOKEN",jsonToken.get("access_token").toString());
            var s = HttpUtils.sendGet(lastUrl);
            var jsonObject = GsonUtils.strJsonObject(s);
            if (null != jsonObject.get("errcode")) {
                redisUtil.set("menus_delete", s);
            }
            log.info("公众号返回的数据为:{}",s);
        }
    }

    /**
     * 创建菜单
     * @param accessToken
     * @return json
     */
    public void obtainCreateMenus(){
        var url = CustomizedPropertyConfigurer.getContextProperty("menu.create,new.url");
        if(accessToken.isEmpty() && accessToken.isBlank()){
            obtainWechatToken();
        }
        var jsonToken = GsonUtils.strJsonObject(accessToken);
        if(null!=jsonToken && jsonToken.isJsonObject() && null == jsonToken.get("errcode")) {
            var param = "access_token="+jsonToken.get("access_token").toString();
            var s = HttpUtils.sendGet(url,param);
            var jsonObject = GsonUtils.strJsonObject(s);
            if (null != jsonObject.get("errcode")) {
                redisUtil.set("menus_create", s);
            }
            log.info("公众号返回的数据为:{}", s);
        }
    }
    @PostConstruct
    public void initToken(){
        Object token = redisUtil.get("token");
          if (token == null) {
              obtainWechatToken();
             // obtainJsApiTicket();
             // obtainOpenId();
             // obtainGetMenus();
             // obtainCreateMenus();
          }
    }
}
